package com.homework.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CountListener implements ServletContextListener{
	//文件存放的文件夹名
	public static final String FILE_POSITION = "postion";
	public static final String TXT_POSITION = "count.txt";
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		//1.获取application中的count的值
		ServletContext sc = sce.getServletContext();
		Object count = sc.getAttribute("count");
		//1.1判断count是否为空，但index.jsp已经判断一定有count这个对象,但如果直接开启服务器，并关闭
		//会为空，还是要判断
		if(count!=null){
			//2写出到本地的路径中
			//2.1获取本地路径
			String filePath = sc.getRealPath("/")+FILE_POSITION+File.separator;
			File filePathDirs = new File(filePath);
			//2.1.1判断filePathDirs这个文件夹是否存在
			if(!filePathDirs.exists()){
				System.out.println("创建文件夹");
				//不存在，创建该文件夹
				filePathDirs.mkdirs();
			}
			//2.2txt文件的路径
			String txtFile = filePath + TXT_POSITION;
			//2.2.1创建txt文件
			File txtFileDirs = new File(txtFile);
			if(!txtFileDirs.exists()){
				//不存在就创建该文件
				System.out.println("创建txt文件");
				try {
					txtFileDirs.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//3.写出count值
			//3.1创建输出流
			FileOutputStream outPut =null;
			//3.2写入
			try {
				outPut = new FileOutputStream(txtFileDirs);
				outPut.write((count+"").getBytes());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
	
		//从保存的文件txt中 读取相应的数据
				ServletContext application=sce.getServletContext();
				//文件
				String filePath= application.getRealPath("/")+FILE_POSITION+File.separator;
				
				File countFile = new File(filePath+TXT_POSITION);
				
				if(countFile.exists()){
					byte[] b = new byte[1024];
					
					try {
						FileInputStream input = new FileInputStream(countFile);
						
						while(input.read(b)==-1){
							
						}
						String s = new String(b);
						s = s.trim();
						int count = Integer.valueOf(s);
						//System.out.println(count);
						application.setAttribute("count", count);							
						//这个内容一次性读到数组里面
//						
//						while((result=input.read(bytes))==-1){
//							// count = Integer.parseInt(bytes.toString());
//							count += bytes;
//						}
//						System.out.println(count);
//					
					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
					}
				}

	}

}
